package user

import (
	"data/config"
	"data/view"
	"data/view/auth/auth_const"
	"encoding/json"
	"public/mycache"
	"public/myhttp"
	"public/mylog"
	"public/mysqldb"
	"public/tools"
	"strconv"
	"time"
)

//通过token获取用户信息
func GetUserFromToken(token string) (username string, expire_time int, b bool) {
	b = false
	if len(token) == 0 {
		return
	}

	//先从缓存中获取
	cache := mycache.OnGetCache("oauth2")
	var tp interface{}
	tp, b = cache.Value(token)

	if b {
		tmp := tp.(*view.UserCacheBody)
		username = tmp.User_name
		expire_time = tmp.Expire_time
		return
	} else {
		parm := make(map[string]string)
		parm["token"] = token
		bod, _ := json.Marshal(parm)
		r_body := myhttp.OnPostJson(config.GetCheckTokenUrl(), string(bod))
		if len(r_body) == 0 {
			return
		} else {
			var msg view.MapMessageBody
			json.Unmarshal([]byte(r_body), &msg)
			b = msg.State
			if msg.State {
				//成功
				var tmp view.UserCacheBody
				tmp.Access_token = token
				tmp.User_name = msg.Data["username"]
				tmp.Expire_time, _ = strconv.Atoi(msg.Data["expire_time"])

				//保存缓存
				cache := mycache.OnGetCache("oauth2")
				cache.Add(tmp.Access_token, &tmp, time.Duration(tmp.Expire_time)*time.Second)
				//------------------end

				//返回结果
				username = tmp.User_name
				expire_time = tmp.Expire_time
			}
			return
		}
	}
	//------------------end
}

//通过token 获取 用户信息
func GetUserDetailFromToken(token string) (user User_tbl, b bool) {
	var username string
	username, _, b = GetUserFromToken(token)
	if b {
		return GetUserDetail(username)
	}

	return
}

//获取用户基本信息
func GetUserDetail(username string) (user User_tbl, b bool) {
	b = false
	if len(username) == 0 {
		return
	}
	//先从缓存中获取
	cache := mycache.OnGetCache("user_detail")
	var tp interface{}
	tp, b = cache.Value(username)

	if b {
		user = tp.(User_tbl)
		return
	} else {
		var db mysqldb.MySqlDB
		defer db.OnDestoryDB()
		orm := db.OnGetDBOrm(config.GetDbUrl())

		// orm.Table("user_tbl").Select("parent_user,alias,user,business_role,b_province as topic,b_city as bundle,b_region as pid").
		// Where("user = ?", username).Find(&user)

		orm.Where("user = ?", username).Find(&user)
		if len(user.User) > 0 {
			//保存缓存
			cache.Add(username, user, 24*time.Hour)
			b = true
		}
		return
	}
}

//获取用户详情(老师，或者学生)
func GetUserInfo(username string) (user User_info_tbl, b bool) {
	b = false
	if len(username) == 0 {
		return
	}
	//先从缓存中获取
	cache := mycache.OnGetCache("user_info")
	var tp interface{}
	tp, b = cache.Value(username)

	if b {
		user = tp.(User_info_tbl)
		return
	}

	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())

	// orm.Table("user_tbl").Select("parent_user,alias,user,business_role,b_province as topic,b_city as bundle,b_region as pid").
	// Where("user = ?", username).Find(&user)

	orm.Where("id_card = ?", username).Find(&user)
	if user.Id != 0 {
		//保存缓存
		cache.Add(username, user, 24*time.Hour)
		b = true
	}
	return
}

// //从缓存获取用户信息
// func GetUserInfoFromCache(username string) (user myauthority.UserInfo) {
// 	//判断用户是否存在
// 	cache := mycache.OnGetCache("user_info")
// 	var tp interface{}
// 	tp, ret := cache.Value(username)
// 	if ret {
// 		user = tp.(myauthority.UserInfo)
// 	}
// 	return
// }

// 删除用户缓存
func OnDeleteUserCache(user string) {
	//删除缓存
	cache := mycache.OnGetCache("user_info")
	cache2 := mycache.OnGetCache("user_detail")
	cache.Delete(user)
	cache.Delete("all")
	cache2.Delete(user)
}

//删除用户
func DeleteOneUser(user string) error {
	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())

	tmp := []int{auth_const.R_7}
	_, roleStr := OnGetRoleData(tmp)
	//降级为学生
	mp := map[string]interface{}{"business_role": roleStr}
	err := orm.Table("user_tbl").Where("user = ?", user).Updates(mp).Error

	//删除团队联系
	err = orm.Table("user_team_tbl").Where("user = ?", user).Delete(&view.User_team_tbl{}).Error

	OnDeleteUserCache(user)
	return err
}

//获取全部用户详情
func GetAllUserDetail() (users map[string]User_info_view, b bool) {
	//先从缓存中获取
	cache := mycache.OnGetCache("user_info")
	var tp interface{}
	tp, b = cache.Value("all")

	if b {
		users = tp.(map[string]User_info_view)
		return
	} else {
		var db mysqldb.MySqlDB
		defer db.OnDestoryDB()
		orm := db.OnGetDBOrm(config.GetDbUrl())

		var tmp []User_info_view
		orm.Find(&tmp)
		if len(tmp) > 0 {
			users = make(map[string]User_info_view)
			for _, v := range tmp {
				users[v.User] = v
			}
			//保存缓存
			cache.Add("all", users, 2*time.Hour)
			b = true
		}
		return
	}
}

//判断能否删除用户
func CanDeleteUser(user string) bool {
	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())

	var users []view.Team_info_tbl
	orm.Where("leader like ?", "%"+user+"%").Find(&users)
	if len(users) > 0 {
		return false
	} else {
		return true
	}
}

func GetUserLevel() (result []*User_level_info) {
	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())

	//管理员 auth_const.R_2
	orm.Table("user_info_view").Where("business_role = ?", 2).Find(&result)

	if len(result) > 0 {
		for _, v := range result {
			var team []*User_level_info //团队管理员
			orm.Table("user_info_view").Where("parent_user = ?", v.User).Find(&team)

			if len(team) > 0 {
				for _, k := range team {
					var teacher []*User_level_info //老师
					orm.Table("user_info_view").Where("parent_user = ?", k.User).Find(&teacher)
					k.Children = teacher
				}
			}
			v.Children = team
		}
	}

	return
}

//保存用户
func SaveOneUser(user User_tbl) bool {
	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())

	err := orm.Save(&user).Error
	if err != nil {
		mylog.Error(err)
		return false
	} else {
		return true
	}

}

//保存用户信息
func SaveOneUserWithInfo(user User_tbl, info User_info_tbl) bool {
	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())

	if SaveOneUser(user) {
		err := orm.Save(&info).Error
		if err != nil {
			mylog.Error(err)
			return false
		} else {
			return true
		}
	} else {
		return false
	}

}

//获取角色
func OnGetRoleData(roles []int) (result []Role_info, str string) {
	if len(roles) > 0 {
		rtmp := GetRoleConfigInfo()
		for _, v := range roles {
			result = append(result, Role_info{Role: v, Desc: rtmp[v].Desc})
		}
		str = tools.JsonDecode(result)
	}
	return
}

//获取角色配置信息
func GetRoleConfigInfo() (roles map[int]User_role_tbl) {
	//读取配置信息
	cache := mycache.OnGetCache("auth_role_info")
	obj, b := cache.Value("detail")
	if b {
		roles = obj.(map[int]User_role_tbl)
	} else {
		roles = make(map[int]User_role_tbl)
		var db mysqldb.MySqlDB
		defer db.OnDestoryDB()
		orm := db.OnGetDBOrm(config.GetDbUrl())

		var config []User_role_tbl
		orm.Find(&config)

		if len(config) > 0 {
			for _, v := range config {
				roles[v.Role] = v
			}
		}
		cache.Add("detail", roles, 24*time.Hour)
	}
	return
}

//删除角色cache
func DeleteRoleCache() bool {
	//读取配置信息
	cache := mycache.OnGetCache("auth_role_info")
	err := cache.Delete("detail")
	if err != nil {
		mylog.Error(err)
		return false
	} else {
		return true
	}

}
